<?php

namespace app\api\controller;

use think\worker\Server;
use think\Log;
use think\Queue;
use Workerman\Lib\Timer;
use think\Exception;
use Workerman\Worker;
use think\Loader;

class Workerserver extends Server
{
    protected $socket             = 'websocket://0.0.0.0:4431';
    protected $processes          = 1;
    public static $uidConnections = [];
    protected $d                  = '';
    protected $timer_id           = null;
    protected $context            = array(
        'ssl' => array(
            // 使用绝对路径
            'local_cert'  => '/etc/nginx/cert/213984411530979.pem', // 也可以是crt文件
            'local_pk'    => '/etc/nginx/cert/213984411530979.key',
            'verify_peer' => false,
        )
    );

    public function __construct()
    {
        // 实例化 Websocket 服务
        $this->worker = new Worker($this->socket ?: $this->protocol . '://' . $this->host . ':' . $this->port, $this->context);
        // 设置进程数
        $this->worker->count = $this->processes;
        $this->worker->transport = 'ssl';
        // 初始化
        $this->init();

        // 设置回调
        foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
            if (method_exists($this, $event)) {
                $this->worker->$event = [$this, $event];
            }
        }
        // Run worker
        Worker::runAll();
    }

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        foreach(self::$uidConnections as $conn) {
        try {
            $conn->send($data);
        } catch (\Exception $e) {
            $connection->send($e->messages);
        }
            
        }
        // if ($data == 'q') {
        //     foreach(self::$uidConnections as $conn) {
        //         $conn->send($connection->id . ':' . $this->d);
        //     }
        //     $this->d = '';
        // }else{
        //     $this->d .= $data;
        // }
                
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        self::$uidConnections[$connection->id] = $connection;
        foreach(self::$uidConnections as $conn) {
            try {
                $conn->send($connection->id . ': 上线了');
            } catch (\Exception $e) {}
            
        }
        
        //queue('test/Job@task', $connection);
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        unset(self::$uidConnections[$connection->id]);
        foreach(self::$uidConnections as $conn) {
            try {
                $conn->send($connection->id . ': 掉线了');
            } catch (\Exception $e) {}
        }
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        $time_interval = 10;
        $this->timer_id = Timer::add($time_interval, function() use ($worker)
        {
            foreach(self::$uidConnections as $conn) {
                try {
                    if ($a = Loader::model('Notices')->count()) {
                        $conn->send($a);
                    }
                    
                } catch (\Exception $e) {}
            }
            foreach($worker->connections as $connection)
            {
                //$connection->send($connection->id . '|' . time());
            }
        });
    }

    public function onWorkerStop($worker)
    {
        # code...
    }
}